﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class ModuleDefinitionRule : ILRule<ModuleDefinitionHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        [ILInfo]
        public Guid BaseGenerationId { get; }

        [ILInfo]
        public int Generation { get; }

        [ILInfo]
        public Guid GenerationId { get; }

        [ILInfo]
        public Guid Mvid { get; }

        public ModuleDefinitionRule(
            int generation,
            string moduleName,
            Guid mvid,
            Guid encId,
            Guid encBaseId)
            : base()
        {
            Generation = generation;
            Name = moduleName;
            Mvid = mvid;
            GenerationId = encId;
            BaseGenerationId = encBaseId;
        }

        public ModuleDefinitionRule(MetadataReader reader)
            : base(reader)
        {
            ModuleDefinition moduleDefinition = reader.GetModuleDefinition();
            BaseGenerationId = reader.GetGuid(moduleDefinition.BaseGenerationId);
            Generation = moduleDefinition.Generation;
            GenerationId = reader.GetGuid(moduleDefinition.GenerationId);
            Mvid = reader.GetGuid(moduleDefinition.Mvid);
            Name = reader.GetString(moduleDefinition.Name);
        }

        public override ModuleDefinitionHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddModule(
                generation: Generation,
                moduleName: Name == null ? default : builder.GetOrAddString(Name),
                mvid: builder.GetOrAddGuid(Mvid),
                encId: builder.GetOrAddGuid(GenerationId),
                encBaseId: builder.GetOrAddGuid(BaseGenerationId));
        }
    }
}